import { defineStore } from 'pinia'
import { ref, computed } from 'vue';
import { useRouter, RouteLocationRaw, Router } from 'vue-router';

type Admin = {
	"id": number,
	"name": string,
	"password": null,
	"email": string,
	"createTime": string,
	"updateTime": string,
	"state": number,
}

interface MyRoute {
	key: string,
	title: string,
}

const getFormatRoutes = (router: Router): MyRoute[] => {
	const routes: MyRoute[] = []
	router.getRoutes().filter(route => route.name).forEach(route => {
		const e:MyRoute = {
			key: route.name as string,
			title: route.meta.title as string,
		}
		routes.push(e)
	})
	return routes;
}

const useBaseStore = defineStore('baseStore', () => {
	const router = useRouter();
	const routes = getFormatRoutes(router)

	const route = ref<string>('')
	const counter = ref<number>(0)
	const admin = ref<Admin | null>(null)
	const token = ref<string>('')

	const getRoute = computed(() => route.value)
	const getAdmin = computed(() => admin.value)
	const getToken = computed(() => token.value)
	const isLogin = computed(() => admin.value === null ? false : true)



	const logout = () => {
		admin.value = null;
		token.value = ''
		localStorage.removeItem('token');
	}
	const incr = () => { counter.value++ }
	const getTargetRoute = (key: string) => {
		return routes.find(e => e.key === key)
	}
	const updateRoute = async (routeLocationRaw: RouteLocationRaw) => {
		await router.push(routeLocationRaw)
		route.value = router.currentRoute.value.path.replace('/', '')
		console.log('route: ' + route.value);
	}
	const setAdmin = (a: Admin | null) => {
		if (a == null) {
			throw new Error('admin is null');
		}
		admin.value = a;
	}
	const setToken = (t: string) => {
		token.value = t;
		saveToken()
	}
	const saveToken = () => {
		localStorage.setItem('token', token.value)
	}
	const loadToken = () => {
		token.value = localStorage.getItem('token') || ''
	}


	return {
		counter, route, admin,
		incr, getRoute, getAdmin, getToken, logout, isLogin,
		setAdmin, setToken,
		saveToken, loadToken, updateRoute, getTargetRoute
	}
})


export default useBaseStore;
